﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.NewHouse.Controllers
{
    [Description("管理-户型")]
    public class HouseTypeController : BaseController
    {
        public IHouseTypeContract HouseTypeContract { get; set; }
        public IBuildingsContract BuildingsContract { set; get; }
        #region 户型列表
        [Description("管理-户型列表")]
        public ActionResult Index()
        {
            
            return View();
        }
        [HttpPost]
        public ActionResult IndexAsync(int pageIndex, int pageSize, int id, string search = "")
        {
            var query = HouseTypeContract.TrackEntities.Where(m => !m.IsDeleted && m.BuildingID == id); 
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Name.Contains(search));
            }
            var data = from hq in query
                       select new
                       {
                           id = hq.Id,
                           Building = (from b in BuildingsContract.TrackEntities where hq.BuildingID == b.Id select b.Name).FirstOrDefault(),
                           Name = hq.Name,
                           Area = hq.Area,
                           Room = hq.Room,
                           Hall = hq.Hall,
                           Toilet = hq.Toilet,
                           Inventory = hq.Inventory,
                           SalesVolume = hq.SalesVolume,
                           Price = hq.Price,
                           Preferential = hq.Preferential,
                           Orientations = hq.Orientations,
                           DecorationCondition = hq.DecorationCondition,
                           Reason = hq.Reason,
                           ShowIndex = hq.ShowIndex,
                           Remark = hq.Remark,
                           IsLocked = hq.IsLocked,
                           IsDeleted = hq.IsDeleted,
                           CreatedTime = hq.CreatedTime,
                       }; 
            //数据总数
            var total = data.Count();

            //默认给一个排序的字段
            data = data.OrderByDescending(m => m.id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            data = total > 0 ? data.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : data;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = data.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion 

        #region 户型添加
        [Description("管理-户型添加")]
        public ActionResult Insert(int id)
        {
            var entity = BuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [HttpPost]
        public ActionResult InsertAsync(HouseType entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            Random ran = new Random();
            int a = ran.Next(1, 100);
            entity.SalesVolume = a;
            entity.ShowIndex = 0;
            try
            {
                var count = HouseTypeContract.Insert(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "录入成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "录入失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 户型修改
        [Description("管理-户型修改")]
        public ActionResult Edit(int id, int Properties)
        {
            var bentity = BuildingsContract.GetByKey(Properties);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (bentity == null) throw new Exception("未找到该实体");
            ViewData["bentity"] = bentity;
            var entity = HouseTypeContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditAsync(HouseType entity)
        {
            var result = new AjaxResult();
            try
            { 
                    var count = HouseTypeContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    } 
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 户型删除
        [Description("管理-户型删除")]
        [HttpPost]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                HouseTypeContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new HouseType { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        } 
        #endregion
    }
}